package com.xmall.controller.wx;

import com.xmall.bean.table.User;
import com.xmall.bean.vo.BaseRespVo;
import com.xmall.bean.vo.WxLoginUserInfoVo;
import com.xmall.bean.vo.WxLoginVo;
import com.xmall.mapper.UserMapper;
import com.xmall.shiro.MallToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.Date;
import java.util.Map;

@Controller("wxAuthController")
@RequestMapping("wx/auth")
public class AuthController {

    @Autowired
    UserMapper userMapper;

    @PostMapping("login")
    @ResponseBody
    public BaseRespVo login(@RequestBody Map map) {
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        MallToken token = new MallToken(username, password, "wx");
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        Serializable sessionId = subject.getSession().getId();
        User user = (User) subject.getPrincipal();
        WxLoginUserInfoVo userInfoVo = new WxLoginUserInfoVo(username, user.getAvatar());
        WxLoginVo wxLoginVo = new WxLoginVo(sessionId.toString(), new Date().toString(), userInfoVo);
//        User user = (User) subject.getPrincipal();
        return BaseRespVo.ok(wxLoginVo);

    }

    @RequestMapping("logout")
    @ResponseBody
    public BaseRespVo logout(HttpSession session) {
        session.invalidate();
        return BaseRespVo.ok();
    }

}
